package k.web.cityManage;

import com.alibaba.fastjson.JSON;
import k.HelperClazz;
import k.activiti.dto.WorkFlow;
import k.activiti.service.EasyActService;
import k.dao.base.GridDao;
import k.dto.Emp;
import k.dto.Event;
import k.dto.Grid;
import k.service.EventService;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;


/**
 * Created by sure on 2018/4/12.
 */
@Controller
@RequestMapping(value = "/work")
public class WorkController {
    @Autowired
    private EasyActService easyActService;
    @Autowired
    private EventService eventService;
    @Autowired
    private GridDao gridDao;

    /**
     * 组任务管理主页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/zworkIndex")
    public String zworkIndex(Model model, HttpServletRequest request) {
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        model.addAttribute("GroupList", eventService.findGroupList(HelperClazz.getEMP()));
        return "system_manage/zworkIndex";
    }

    /**
     * 个人任务主页面
     */
    @RequestMapping(value = "/gworkIndex")
    public String gworkIndex(Model model, HttpServletRequest request) {
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        model.addAttribute("taskList", eventService.findTaskListByEmpId(HelperClazz.getEMP().getEmp_id().toString()));
        return "system_manage/gworkIndex";
    }

    /**
     * 提交工作流
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/insertEvent")
    public String insertEvent(Model model, HttpServletRequest request) {
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        return "system_manage/insertEvent";
    }

    /**
     * 上报事件
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/addEvent")
    public String addEvent(Model model, HttpServletRequest request) {
        List<Grid> grids =gridDao.queryGrids();
        model.addAttribute("grids", grids);
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        return "system_manage/addEvent";
    }

    /**
     * 发布流程
     *
     * @param file
     * @param filename
     * @return
     */
    @RequestMapping("newdeploy")
    public String newdeploy(MultipartFile file, String filename) {
        filename = "Event";
        System.out.println("发布流程" + filename);
        // 获取页面传递的值
        // 1：获取页面上传递的zip格式的文件，格式是MultipartFile类型
        // 2：调用上传文件方法，存储file
        // 方法返回值为路径+文件名
        String path = easyActService.fileUpload(file);
        // 指向文件路径
        File f = new File(path);
        // 完成部署
        easyActService.saveNewDeploye(f, filename);
        return "redirect:/index";
    }

    /**
     * 查看流程图
     *
     * @param
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "viewImage", method = RequestMethod.GET)
    public void viewImage(String eventId, HttpServletResponse response) throws Exception {
        String taskId = easyActService.findTaskIdByObjecId(Event.class.getSimpleName(), eventId);
        // 1：获取页面传递的部署对象ID和资源图片名称
        // 部署对象ID
        ProcessDefinition pd = easyActService.getProcessDefinitionByTaskId(taskId);
        // 1. 获取流程部署ID
        String deploymentId = pd.getDeploymentId();
//        String deploymentId = workFlow.getDeploymentId();
        // 资源图片名称
        String imageName = pd.getDiagramResourceName();
//        String imageName = workFlow.getImageName();
        // 2：获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
        InputStream in = easyActService.findImageInputStream(deploymentId, imageName);
        // 3：从response对象获取输出流
        OutputStream out = response.getOutputStream();
        // 4：将输入流中的数据读取出来，写到输出流中
        for (int b = -1; (b = in.read()) != -1; ) {
            out.write(b);
        }
        out.close();
        in.close();
        // 将图写到页面上，用输出流写
    }

    @RequestMapping("eventadd")
    public String eventadd(Event event) throws Exception {
        event.setEmp_id(HelperClazz.getEMP().getEmp_id());
        event.setEmp_name(HelperClazz.getEMP().getEmp_name());
        eventService.saveStartProcess(event);//启动流程实例，让启动的流程实例关联业务,开始运作,返回
        return "redirect;/work/addEvent";
    }

    /**
     * 领取任务，组任务变为个人任务
     * Created by 王玉涛
     *
     * @Param taskId, empId
     * @date 2017/6/23 21:49
     */
    @RequestMapping("claim")
    public String claim(String eventId, String empId) {//任务ID,分配的办理人
        String taskId = easyActService.findTaskIdByObjecId(Event.class.getSimpleName(), eventId);
        easyActService.claim(taskId, empId);
        return "redirect;/work/zworkIndex";
    }

    /**
     * 跳转到事件详情
     * Created by 王玉涛
     *
     * @Param taskId, empId
     * @date 2017/6/23 21:49
     */
    @RequestMapping("info")
    public String info(Model model, Integer eventId) {//任务ID,分配的办理人
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        model.addAttribute("eventInfo", eventService.findOne(eventId.toString()));
        model.addAttribute("commentList", easyActService.findCommentByObjecId(Event.class.getSimpleName(), eventId));
        return "system_manage/info";
    }

    /**
     * 跳转到事件详情
     * Created by 王玉涛
     *
     * @Param taskId, empId
     * @date 2017/6/23 21:49
     */
    @RequestMapping("infog")
    public String infog(Model model, Integer eventId) {//任务ID,分配的办理人
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        List<Emp> emps = eventService.getEmps(HelperClazz.getEMP().getOrg_id());
        model.addAttribute("emps", emps);
        model.addAttribute("eventInfo", eventService.findOne(eventId.toString()));
        model.addAttribute("commentList", easyActService.findCommentByObjecId(Event.class.getSimpleName(), eventId));
        String taskId = easyActService.findTaskIdByObjecId(Event.class.getSimpleName(), eventId.toString());
        model.addAttribute("outcomeList", easyActService.findOutComeListByTaskId(taskId));
        return "system_manage/infog";
    }

    /**
     * 完成任务
     * Created by 王玉涛
     *
     * @Param comment为处理意见，id为事件id,empName
     * @date 2017/6/25 18:44
     */
    @RequestMapping("completeTask")
    public String completeTask(String outcome, String empId, String comment, String eventId) {
        String taskId = easyActService.findTaskIdByObjecId(Event.class.getSimpleName(), eventId.toString());
        WorkFlow workFlow = new WorkFlow();
        workFlow.setOutcome(outcome);
        workFlow.setEmp_id(empId);
        workFlow.setComment(comment);
        workFlow.setTaskId(taskId);
        eventService.completeTask(workFlow);
        return "redirect:/work/gworkIndex";
    }

    /**
     * 查询事件
     * @return
     */
    @RequestMapping("queryAllEvent")
    public String queryAllEvent(Model model) {
        List<Event> list = eventService.queryAll();
        model.addAttribute("eventList" ,list);
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        return "system_manage/queryAllEvent";

    }
    /**
     * 查询事件info
     * @return
     */
    @RequestMapping("queryAllEventInfo")
    public String queryAllEventInfo(Model model, Integer eventId) {
        model.addAttribute("emp_id", HelperClazz.getEMP().getEmp_id());
        model.addAttribute("emp_name", HelperClazz.getEMP().getEmp_name());
        model.addAttribute("eventInfo", eventService.findOne(eventId.toString()));
        model.addAttribute("commentList", easyActService.findCommentByObjecId(Event.class.getSimpleName(), eventId));
        return "system_manage/queryAllEventInfo";

    }

    @RequestMapping("zEvent")
    public void zEvent(HttpServletResponse response) {
        HelperClazz.renderJson(response, JSON.toJSONString(eventService.findGroupList(HelperClazz.getEMP())));
    }
}
